'''
注册功能
    1。需要用户名和密码以及确认密码
    2。注册时如果用户名已经存在，则不能再次注册
登录功能
    1。需要使用已经注册的用户信息登录
    2。密码输入错误3次后，锁定账户信息(不能再使用这个账户进行登录操作)
'''

# 操作类型代码
type = input('请输入要进行的操作：\n0 注册\n1 登录\n')
inputFileName = ''
inputFilePassword = ''

# 确认密码函数
def confirmPassword():
    p1 = input('请输入密码：')
    p2 = input('请再次输入密码：')
    if p1 == p2:
        global inputFilePassword
        inputFilePassword = p1
    else:
        print('两次密码输入不一致，请重新输入')
        confirmPassword()
# 判断用户名是否存在与文件中
def usernameInFiles(username):
    usernames = []
    with open('./passwordPlus.txt', 'r+') as fp:
        fp.seek(0)
        for i in fp.readlines():
            usernames.append(i.split('\n')[0].split('-')[0])
    if username in usernames:
        return True
    else:
        return False
# 获取用户名
def getusername():
    username = input('请输入用户名：')
    if usernameInFiles(username):
        print('用户名已存在！请重新输入')
        getusername()
    else:
        global inputFileName
        inputFileName = username

loginUsername = ''
loginPassword = ''
truePassword = ''
userInfoDicts = {}
# 获取并判断用户名是否存在
def loginGetUsername():
    username = input('请输入用户名：')
    if usernameInFiles(username):
        userInfoDict = {}
        with open('./passwordPlus.txt', 'r+') as fp:
            fp.seek(0)
            for i in fp.readlines():
                itemuserinfo = i.split('\n')[0]
                itemusername = itemuserinfo.split('-')[0]
                itemuserpass = itemuserinfo.split('-')[1]
                itemuserstate = itemuserinfo.split('-')[2]
                userInfoDict[itemusername] = f'{itemuserpass}-{itemuserstate}'
        if userInfoDict[username].split('-')[1] == '1':
            print('该账号已被系统锁定，请联系相关人员')
            loginGetUsername()
        else:
            global loginUsername, truePassword, userInfoDicts
            userInfoDicts = userInfoDict.copy()
            loginUsername = username
            truePassword = userInfoDict[username].split('-')[0]
    else:
        print('用户名不存在，请重新输入')
        loginGetUsername()
# 登录验证密码
def loginPassword(n):
    if n > 0:
        password = input('请输入密码：')
        if password == truePassword:
            print('登录成功！')
        else:
            if n-1 > 0:
                print(f'密码不正确，你还有{n-1}次机会。请重新输入：')
            loginPassword(n-1)
    else:
        print('账号已锁定')
        userInfoDicts[loginUsername] = f'{truePassword}-1'
        alluserInfostr = ''
        for i in userInfoDicts:
            alluserInfostr += f'{i}-{userInfoDicts[i]}\n'
        with open('./passwordPlus.txt', 'w+') as fp:
            fp.write(alluserInfostr)

# 判断选择的类型
if type == '0':
    # 注册
    getusername()
    confirmPassword()
    with open('./passwordPlus.txt', 'r+') as fp:
        # 文件指针移动到最后
        fp.seek(0, 2)
        # 写入文件
        fp.write(f'{inputFileName}-{inputFilePassword}-0\n')
        print('注册成功！')
else:
    # 登录
    loginGetUsername()
    loginPassword(3)


